<template>
  <div class="container" style="height: 100%">
    <el-form
      class="query-form query-form-2"
      :model="formQuery"
      style="display: block"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item>
            <el-date-picker
              clearable
              v-model="formQuery.statisticsMonth"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="month"
              placeholder="统计月份"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="4">
          <el-form-item>
            <el-date-picker v-model="formQuery.firstDate" value-format="yyyy-MM-dd HH:mm:ss" type="date"
              placeholder="选择开始日期">
            </el-date-picker>
          </el-form-item>
        </el-col> -->
        <el-col :span="4">
          <el-form-item>
            <el-select
              clearable
              placeholder="缴费状态"
              v-model="formQuery.paymentStatus"
            >
              <el-option value="0" label="待缴费"></el-option>
              <el-option value="1" label="已缴费"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              clearable
              placeholder="发票状态"
              v-model="formQuery.invoiceStatus"
            >
              <el-option value="0" label="未开票"></el-option>
              <el-option value="1" label="已开票"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input
              clearable
              placeholder="承租人"
              v-model="formQuery.inputString"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input
              clearable
              placeholder="联系电话(手机)"
              v-model="formQuery.contactPhone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item style="position: absolute; right: 0.2rem">
            <el-button @click="query" type="primary">查询</el-button>
            <el-button
              type="primary"
              @click="
                isShowInvoice = !isShowInvoice;
                btnStats = 'Kp';
              "
              >开票</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-form-item>
            <el-select
              clearable
              placeholder="出租人"
              v-model="formQuery.fkLessorId"
            >
              <el-option
                v-for="item in lessor"
                :key="item.pkBasicdataId"
                :value="item.pkBasicdataId"
                :label="item.itemName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              clearable
              placeholder="所在楼宇"
              v-model="formQuery.fkBuildingId"
            >
              <el-option
                v-for="item in buildingData"
                :key="item.pkBuildingId"
                :value="item.pkBuildingId"
                :label="item.buildingName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input
              clearable
              placeholder="房间号"
              v-model="formQuery.houseNumber"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input
              clearable
              placeholder="单元编码"
              v-model="formQuery.unitCoding"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="4">
          <el-form-item style="position: absolute; right: 0.2rem">
            <el-button @click="exportReport" type="primary">导出</el-button>
            <el-button @click="expenseLock" type="primary">扎帐</el-button>
            <el-dropdown>
              <el-button type="primary">
                批量抄表<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-upload
                    :action="importUrl"
                    :headers="token"
                    :show-file-list="false"
                    :auto-upload="true"
                    :on-progress="uploadProgress"
                    :on-error="importError"
                    :on-success="importSuccess"
                  >
                    <el-button size="small" type="primary">导入文件</el-button>
                  </el-upload>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="small" type="primary" @click="exportTempFile"
                    >导出模板</el-button
                  >
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              type="primary"
              @click="
                isShowInvoice = !isShowInvoice;
                btnStats = 'Dy';
              "
              >打印
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="div-table" style="padding: 0 20px">
      <el-scrollbar style="height: 100%">
        <el-table
          ref="table"
          class="roomTable"
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            :selectable="selMethod"
            v-if="isShowInvoice"
            type="selection"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="statisticsMonth"
            label="统计月份"
          >
            <template slot-scope="{ row }">
              {{ row.statisticsMonth | timeFormatFilter("yyyy年mm月") }}
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="buildingName"
            label="所在楼宇"
          ></el-table-column>
          <el-table-column prop="houseNumber" label="房间号"></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="tenantName"
            label="承租人"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="lessorName"
            label="出租人"
          ></el-table-column>
          <el-table-column
            prop="expensesReceivable"
            label="应收金额"
          ></el-table-column>
          <el-table-column prop="paymentStatus" label="缴费状态">
            <template slot-scope="{ row }">
              {{ row.paymentStatus | paymentStatusFilter }}
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="paymentTime"
            label="缴费时间"
          ></el-table-column>
          <el-table-column prop="paymentMethod" label="缴费方式">
            <template slot-scope="{ row }">
              {{ row.paymentMethod | paymentMethodFilter }}
            </template>
          </el-table-column>
          <el-table-column prop="meterReadingStatus" label="抄表状态">
            <template slot-scope="{ row }">
              {{ row.meterReadingStatus | meterReadingStatusFilter }}
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="meterReadingTime"
            label="抄表时间"
          ></el-table-column>
          <el-table-column prop="invoiceMethod" label="开票方式">
            <template slot-scope="{ row }">
              {{ row.invoiceMethod | invoiceMethodFilter }}
            </template>
          </el-table-column>
          <el-table-column prop="invoiceStatus" label="发票状态">
            <template slot-scope="{ row }">
              {{
                row.invoiceStatus
                  | invoiceStatusFilter(row.monthlyInvoiceStatus)
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <!-- 待抄表 -->
              <template v-if="row.meterReadingStatus == '0'">
                <router-link
                  class="el-link el-link--primary"
                  :to="{ path: `/cost/meterReading/` + row.pkExpenseManagId }"
                >
                  抄表
                </router-link>
              </template>
              <!-- 已抄表 并且未被审核 发票状态为NUll的-->
              <template v-else-if="!row.invoiceStatus">
                <router-link
                  class="el-link el-link--primary"
                  :to="{ path: `/cost/edit/${row.pkExpenseManagId}/true` }"
                >
                  审核
                </router-link>
              </template>

              <!-- 线下开票 并且待开票时 -->
              <template
                v-if="row.invoiceMethod == '1' && row.invoiceStatus == '0'"
              >
                <el-link
                  type="primary"
                  :underline="false"
                  @click="
                    () => {
                      showInvoiceId = row.pkExpenseManagId;
                      changeInvoiceStatus(row.invoiceMethod);
                    }
                  "
                >
                  已开发票
                </el-link>
              </template>

              <!-- 未缴费的可以缴费 -->
              <el-link
                type="primary"
                :underline="false"
                v-if="row.paymentStatus == '0'"
                @click="
                  payForm.statisticsMonth = row.statisticsMonth;
                  payForm.fkContractId = row.fkContractId;
                  dialogPayVisible = true;
                  showPayId = row.pkExpenseManagId;
                  payForm.expensesReceivable = row.expensesReceivable;
                  payForm.pkExpenseManagId = row.pkExpenseManagId;
                "
              >
                缴费
              </el-link>
              <!-- <el-link type="primary" :underline="false" v-if="row.invoiceStatus=='0'&&row.paymentStatus=='1'"
                    @click="dialogInvoiceVisible=true;showInvoiceId=row.pkExpenseManagId">
                    线下开票
                    </el-link> -->
              <router-link
                class="el-link el-link--primary"
                :to="{ path: `/cost/edit/` + row.pkExpenseManagId + '/false' }"
              >
                详情
              </router-link>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </div>
    <div class="page-div-placeholder"></div>
    <div class="page-div" style="background: #fff">
      <el-pagination
        layout="prev, pager, next,jumper,sizes"
        :current-page="pageObj.page"
        :page-size="pageObj.pageSize"
        :total="pageObj.total"
        @current-change="currentPageChange"
        @size-change="sizeChange"
        :page-sizes="pageObj.pageSizes"
      ></el-pagination>
      <div
        v-if="isShowInvoice"
        style="position: fixed; right: 10px; bottom: 10px"
      >
        <el-button v-if="btnStats == 'Kp'" type="success" @click="openInvoice"
          >确认</el-button
        >
        <el-button v-else-if="btnStats == 'Dy'" type="success" @click="Printing"
          >确认</el-button
        >
        <el-button @click="isShowInvoice = false">取消</el-button>
      </div>
    </div>
    <!-- 缴费弹窗 -->
    <el-dialog
      class="dialog"
      :show-close="false"
      width="500px"
      title="缴费信息"
      :destroy-on-close="true"
      :visible.sync="dialogPayVisible"
    >
      <el-form
        style="margin-left: 10%; width: 80%"
        ref="payForm"
        :rules="payRule"
        :model="payForm"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="经手人">
              <el-input disabled :value="Handler"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="应收金额">
              <el-input disabled :value="payForm.expensesReceivable">
                <template slot="suffix">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="实收金额" prop="paidInExpenses">
              <el-input v-model="payForm.paidInExpenses">
                <template slot="suffix">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缴费凭证">
              <up-img
                v-model="payForm.paymentVoucher"
                :enlarge="false"
                imgWidth="100%"
                imgHeight="2rem"
                :imgLength="1"
                btnImg="/static/images/title-deed-icon.png"
                ref="uploadImg"
              ></up-img>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缴费说明" prop="paymentInstruction">
              <el-input
                placeholder="请填写"
                v-model="payForm.paymentInstruction"
                show-word-limit
                maxlength="200"
                type="textarea"
                :rows="3"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-button
              :loading="payHanSubmit"
              type="primary"
              style="margin-right: 20px"
              @click="paySubmit"
              >确定
            </el-button>
            <el-button @click="dialogPayVisible = false">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 进度条 -->
    <el-dialog
      title="开票中..."
      :close-on-click-modal="false"
      :visible.sync="openVisible"
      :show-close="false"
      width="35%"
    >
      <el-progress :percentage="percentage"></el-progress>
    </el-dialog>

    <!-- 导出 -->
    <el-dialog
      class="dialog"
      :show-close="false"
      width="500px"
      title="导出"
      :destroy-on-close="true"
      :visible.sync="dialogExportVisible"
    >
      <el-form
        style="margin-left: 15px; width: 90%"
        ref="exportForm"
        :rules="exportRules"
        :model="exportModel"
        label-width="50px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="报表" prop="type">
              <el-radio-group v-model="exportModel.type">
                <el-radio :label="1">汇总表</el-radio>
                <el-radio :label="2">客户分类明细表</el-radio>
                <el-radio :label="3">欠款明细表</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="exportModel.type != 3">
            <el-form-item label="时间" prop="dates">
              <el-date-picker
                v-model="exportModel.dates"
                type="monthrange"
                align="right"
                unlink-panels
                clearable
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                :picker-options="exportMonthOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="exportModel.type == 3">
            <el-form-item label="时间" prop="date">
              <el-date-picker
                v-model="exportModel.date"
                type="month"
                clearable
                placeholder="请选择月份"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="区域" prop="dates">
              <el-select
                clearable
                multiple
                collapse-tags
                v-model="exportModel.areaNumberIds"
                placeholder="区域"
                @change="areaChange"
              >
              <el-option
                  label="全选"
                  :value="areaAllValue"
                  v-if="area.length > 0"
                  @click.native="
                    selectAllArea(
                      exportModel.areaNumberIds.length < area.length
                    )
                  "
                ></el-option>
                <el-option
                  v-for="item in area"
                  :key="item.pkBasicdataId"
                  :value="item.pkBasicdataId"
                  :label="item.itemName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-button
              :loading="exportLoading"
              type="primary"
              style="margin-right: 20px"
              @click="exportSubmit"
              >确定
            </el-button>
            <el-button
              :loading="exportLoading"
              @click="dialogExportVisible = false"
              >取消</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import { getBuildingName } from "@/api/house/building/building.js";
import { getNoticeByContractId } from "@/api/operations/cost/cost";
import { timeFormatFilter } from "@/filters/index.js";
import { getOneAll, selectNameToId, getUserInfo } from "@/api/common/common";
import {
  pay,
  invoicing,
  getInvoicing,
  offlineInvoicing,
  getAllByExpenseManag,
  getAllExpenseManagByCondition,
  expenseLock,
} from "@/api/operations/cost/cost.js";
import upImg from "@/components/upImg";
import { listMixin } from "@/mixin";
import { formatDateTime } from "@/utils/dateTimeHelper";

export default {
  mixins: [listMixin],
  computed: {
    Handler() {
      let userInfo = getUserInfo();
      if (userInfo) {
        return userInfo.name;
      } else {
        return "";
      }
    },
  },
  components: {
    upImg,
  },
  data() {
    return {
      loading: {},
      importUrl: "/baseApicost/importMeterReadingInformations",
      token: { token: this.$store.state.user.token },
      //开票进度条展示
      openVisible: false,
      //开票进度百分比
      percentage: 0,
      payHanSubmit: false,
      btnStats: "Dy",
      //是否显示多选框
      isShowInvoice: false,
      showPayId: 0,
      showInvoiceId: 0,
      payForm: {
        fkContractId: 0,
        handler: null,
        expensesReceivable: 0,
      },
      payRule: {
        paidInExpenses: [
          {
            required: true,
            message: "请输入实收金额",
          },
        ],
        paymentVoucher: [
          {
            required: true,
            message: "请上传缴费凭证",
          },
        ],
        paymentInstruction: [
          {
            required: true,
            message: "请输入缴费说明",
          },
        ],
      },
      dialogPayVisible: false,
      area: [],
      dialogExportVisible: false,
      exportLoading: false,
      exportRules: {
        type: [
          {
            required: true,
            message: "请选择导出报表类型",
          },
        ],
        dates: [
          {
            required: true,
            message: "请选择时间",
          },
        ],
        date: [
          {
            required: true,
            message: "请选择时间",
          },
        ],
        areaNumberIds: [
          {
            required: true,
            message: "请选择区域",
          },
        ],
      },
      exportMonthOptions: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            },
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      exportModel: {
        type: 1,
        dates: null,
        date: null,
        areaNumberIds: [],
      },
      areaAllValue: "ffffffff-ffff-ffff-ffff-ffffffffffff",
      formQuery: {
        statisticsMonth: null,
        invoiceStatus: null,
        contactPhone: null,
        fkBuildingId: null,
        houseNumber: null,
        unitCoding: null,
        paymentStatus: null,
      },
      lessor: [],
      buildingData: [],
      tableData: [],
    };
  },
  methods: {
    expenseLock() {
      expenseLock().then((res) => {
        if (res.code === 10000) {
          this.$message.success(res.msg);
        }
      });
    },
    exportTempFile() {
      window.open(
        "/baseApicost/downloadTempFile?token=" + this.$store.state.user.token
      );
    },
    uploadProgress() {
      this.loading = Loading.service({
        target: ".container",
        text: "数据上传中..",
      });
    },
    importError() {
      this.loading.close();
      this.$message.error("数据导入失败");
    },
    importSuccess(response, file, fileList) {
      this.loading.close();
      if (response.code === 10000) {
        this.$message.info("数据导入成功");
      } else {
        this.$message.error(response.msg);
      }
    },
    selMethod(row, i) {
      if (this.btnStats == "Kp") {
        //未开票
        return row.invoiceStatus == "0";
      }
      return true;
    },
    loadData() {
      if (this.where) {
        return getAllExpenseManagByCondition(this.where).then((res) => {
          let { data, total } = res;
          this.tableData = data;
          this.pageObj.total = total;
        });
      } else {
        return getAllByExpenseManag(this.pageObj).then((res) => {
          let { data, total } = res;
          this.tableData = data;
          this.pageObj.total = total;
        });
      }
    },
    //开票方法
    openInvoice() {
      let tableData = this.$refs["table"].selection;
      if (tableData.length < 1) {
        this.$message.warning("请选择需要开票的费用单据");
        return;
      }

      this.openVisible = true;
      let promises = [];
      tableData.forEach((item) => {
        let p = new Promise((resolve, reject) => {
          invoicing(item.pkExpenseManagId).then((res) => {
            if (res.code === 10000) {
              /**
               * 后端会返回真正的开票接口
               * 这边要做的就是代理访问真正的开票接口（后端访问不到外网，前端nginx代理可以）
               * 然后把返回值再返回给后端
               * */
              let number = res.data.orderNumber;
              let order = res.data.order;
              order = order.replace(/\r\n/g, "");
              /**
               * 不使用FormData包装传递会出错
               * 代码问题，不知道为什么。猜测是全局axios设置导致
               */
              let body = new FormData();
              body.append("order", order);
              axios({
                method: "post",
                url: res.data.url,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                data: body,
              })
                .then((res) => {
                  let i_body = new FormData();
                  i_body.append("orderNumber", number);
                  i_body.append("result", JSON.stringify(res));
                  getInvoicing(i_body).then((res) => {
                    resolve();
                    //单个接口完成时，进度 + 1的百分比
                    this.percentage += Number(
                      ((1 * 100) / tableData.length).toFixed(2)
                    );
                  });
                })
                .catch((msg) => {
                  reject();
                  this.$message.error("开票失败，请稍后重试");
                });
            } else {
              reject();
              this.$message.error(res.msg);
            }
          });
        });
        promises.push(p);
      });
      Promise.all(promises).finally(() => {
        //在所有发票结束后刷新
        this.openVisible = false;
        this.loadDataProxy();
      });
    },
    //打印方法
    Printing() {
      let tableData = this.$refs["table"].selection;
      if (tableData.length < 1) {
        this.$message.warning("请选择需要打印的费用单据");
        return;
      }
      let promises = [];
      var template = `<style>
                            *{font-size:14px;}
                            .zm-title{ font-size:20px;text-align:center; }
                            .hh:nth-child(2){padding-top:105px;}
                            P{margin:5px 0;}
                            table{width:100%;border:1px solid #e6e6e6;}
                            table td,table th{font-weight:500;border:1px solid #e6e6e6;line-height:22px;padding-left:10px;min-width:10px}
                            @page { size: portrait; }
                            .fy{page-break-before:always;}
                    </style>`;
      var html = [];
      tableData.forEach((item) => {
        var id = item.pkExpenseManagId;
        let p = new Promise((resolve, reject) => {
          getNoticeByContractId(id).then((res) => {
            if (res.code != 10000) {
              resolve();
            } else {
              var data = res.data;
              html.push(
                `
                        <div class="hh">
                        <p class="zm-title">中煤南方能源有限公司物业收费通知单</p>
                        <p>
                            <span>合同:${data.contractNumber || ""}</span>
                            <span>承租人:${data.tenantName || ""}</span>
                            <span>地址:${data.address || ""}</span>
                        </p>
                        <table border="1" cellspacing="0">
                            <tr>
                            <td>单元编码 </td>
                            <td>${data.roomNomber || ""}</td>
                            <td>水费编码 </td>
                            <td>${data.waterCostCode || ""}</td>
                            <td>电费编码 </td>
                            <td>${data.electricCostCode || ""}</td>
                            <td>气费编码 </td>
                            <td>${data.coalGasCostCode || ""}</td>
                            </tr>
                        </table>
                        <p class="f-18">
                            水电煤气收费日期截至到 ${timeFormatFilter(
                              data.expenseMonth,
                              "yyyy年mm月"
                            )}，以行度为准。若有疑问，请电:25122920
                        </p>
                        <table border="1" cellspacing="0">
                            <tr>
                            <th colspan="2">水费</th>
                            <th colspan="2">电费</th>
                            <th colspan="2">煤气费</th>
                            <th colspan="2">其他费用</th>
                            </tr>
                            <tr>
                            <td>本月行度 </td>
                            <td>${data.monthWaterMobility || ""}</td>
                            <td>本月行度 </td>
                            <td>${data.monthElectricityMobility || ""}</td>
                            <td>本月表数 </td>
                            <td>${data.monthGasMobility || ""}</td>
                            <td>房租 </td>
                            <td>${data.monthlyRent || ""}</td>
                            </tr>
                            <tr>
                            <td>上月行度 </td>
                            <td>${data.lastMonthWaterMobility || ""}</td>
                            <td>上月行度 </td>
                            <td>${data.lastMonthElectricityMobility || ""}</td>
                            <td>上月表数 </td>
                            <td>${data.lastGasMobility || ""}</td>
                            <td>电话费</td>
                            <td>${data.telephoneRate || ""}</td>
                            </tr>
                            <tr>
                            <td>用水量 </td>
                            <td>${data.waterConsumption || ""}</td>
                            <td>倍率 </td>
                            <td>${data.electricRate || ""}</td>
                            <td>本月用气量</td>
                            <td>${data.monthGasConsumption || ""}</td>
                            <td>综合管理费</td>
                            <td>${data.comprehensiveManagementRate || ""}</td>
                            </tr>
                            <tr>
                            <td>水损(量) </td>
                            <td>${data.waterLossConsumption || ""}</td>
                            <td>公共用电分摊 </td>
                            <td>${data.publicElectricitySharing || ""}</td>
                            <td>第一档单价</td>
                            <td>${data.oneUnitPrice || ""}</td>
                            <td>电梯费</td>
                            <td>${data.elevatorRate || ""}</td>
                            </tr>
                            <tr>
                            <td>指标内水价${data.lessThanWater || ""}内 </td>
                            <td>${data.lessUnitPriceOfWater || ""}</td>
                            <td>实际用量 </td>
                            <td>${data.electricActualConsumption || ""}</td>
                            <td>第二档单价</td>
                            <td>${data.twoUnitPrice || ""}</td>
                            <td>垃圾处理费</td>
                            <td>${data.trashHandlingFee || ""}</td>
                            </tr>
                            <tr>
                            <td>指标外水价${data.lessThanWater || ""}-${
                  data.greaterThanWater || ""
                } </td>
                            <td>${data.middleUnitPriceOfWater || ""}</td>
                            <td>
                                <${
                                  data.lessElectricityConsumption || ""
                                }度单价 </td>
                            <td>${data.lessUnitPriceOfElectricity || ""}</td>
                            <td>第三档单价</td>
                            <td>${data.threeUnitPrice || ""}</td>
                            <td>排水费</td>
                            <td>${data.drainageFee || ""}</td>
                            </tr>
                            <tr>
                            <td>实际单价${data.greaterThanWater || ""}以上 </td>
                            <td>${data.greaterUnitPriceOfWater || ""}</td>
                            <td>${data.lessElectricityConsumption || ""}-${
                  data.greaterElectricityConsumption || ""
                }度单价 </td>
                            <td>${data.middleUnitPriceOfElectricity || ""}</td>
                            <td>气费</td>
                            <td>${data.gasShortage || ""}</td>
                            <td>卫生费</td>
                            <td>${data.sanitationFee || ""}</td>
                            </tr>
                            <tr>
                            <td>加压管理费 </td>
                            <td>${data.pressureAdministrationCosts || ""}</td>
                            <td>>${
                              data.greaterElectricityConsumption || ""
                            }度单价 </td>
                            <td>${data.greaterUnitPriceOfElectricity || ""}</td>
                            <td>欠费</td>
                            <td>${data.gasArrears || ""}</td>
                            <td>煤气保险费</td>
                            <td>${data.gasInsurance || ""}</td>
                            </tr>
                            <tr>
                            <td>水费税金 </td>
                            <td>${data.waterTariff || ""}</td>
                            <td></td>
                            <td></td>
                            <td>换表费</td>
                            <td>${data.gasChangeWatchSpense || ""}</td>
                            <td></td>
                            <td></td>
                            </tr>
                            <tr>
                            <td>小计 </td>
                            <td>${data.waterRentSubtotal || ""}</td>
                            <td>小计 </td>
                            <td>${data.electricRentSubtotal || ""}</td>
                            <td>小计</td>
                            <td>${data.gasRentSubtotal || ""}</td>
                            <td>小计</td>
                            <td>${data.otherSubtotal || ""}</td>
                            </tr>
                            <tr>
                            <td colspan="2">人民币总额 </td>
                            <td colspan="6">${data.totalAmount || ""}</td>
                            </tr>
                        </table>
                        <p>
                            注:以上款项应在每月15日前交纳，迟交加收滞纳金0.5%;并停止供水供电及其他服务
                        </p>
                        <p>
                            户名:中煤南方能源有限公司 开户行:中行人民南路支行 账号:752357951315
                        </p>
                        <p>
                            户名:中煤南方能源有限公司 开户行:工商银行莲塘支行 账号:4000026419200033757
                        </p>
                        <p>
                            户名:深圳市燕美工贸有限公司 开户行:中国银行深圳宝安支行营业部 账号:756257932181
                        </p>
                        <p>
                            我司已开通微信公众号:中煤微物业，客户通过公众号在线缴费，如需开通缴费账户请与管理处联系
                        </p>
                        </div>
                        `
              );
              resolve();
            }
          });
        });
        promises.push(p);
      });
      //所有打印资料获取成功后，打印
      Promise.all(promises).finally(() => {
        for (var i = 0; i < html.length; i += 2) {
          if (html[i]) template += "<div class='fy'>" + html[i];
          if (html[i + 1]) template += html[i + 1];
          template += "</div>";
        }
        var newWin = window.open();
        newWin.document.body.innerHTML = template; //将打印的部分赋值给新打开的标签页
        newWin.window.print(); //执行打印
        newWin.window.close(); //关闭打印窗口
      });
    },
    paySubmit() {
      let obj = { notice: this.payForm };
      obj.fkContractId = this.payForm.fkContractId;
      obj.pkExpenseManagId = this.payForm.pkExpenseManagId;
      obj.notice.handler = this.Handler;
      obj.statisticsMonth = this.payForm.statisticsMonth;
      obj.expensesReceivable = this.payForm.expensesReceivable;
      obj.paidInExpenses = this.payForm.paidInExpenses;
      obj.paymentInstruction = this.payForm.paymentInstruction;
      obj.paymentVoucher = this.payForm.paymentVoucher;
      this.$refs["payForm"].validate((valid) => {
        if (valid) {
          this.payHanSubmit = true;
          this.$refs["uploadImg"].submit().then((res) => {
            pay(obj)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success(res.msg);
                  this.dialogPayVisible = false;
                  this.loadDataProxy();
                }
              })
              .finally((_) => {
                this.payHanSubmit = false;
              });
          });
        }
      });
    },
    changeInvoiceStatus(im) {
      let obj = { pkExpenseManagId: this.showInvoiceId, invoiceMethod: im };
      offlineInvoicing(obj).then((res) => {
        if (res.code === 10000) {
          this.$message.success(res.msg);
          this.loadDataProxy();
        }
      });
    },
    exportReport() {
      const _this = this;
      _this.dialogExportVisible = true;
      _this.exportModel.type = 1;
      _this.exportModel.dates = null;
      _this.exportModel.date = null;
      _this.selectAllArea(true);
    },
    exportSubmit() {
      const _this = this;

      let startDate = "",
        endDate = "";

      if (_this.exportModel.type == 1 || _this.exportModel.type == 2) {
        if (!!_this.exportModel.dates && _this.exportModel.dates.length > 0) {
          startDate = formatDateTime(_this.exportModel.dates[0], "yyyyMM");
          endDate = formatDateTime(_this.exportModel.dates[1], "yyyyMM");
        }
      } else if (_this.exportModel.type == 3) {
        startDate = formatDateTime(_this.exportModel.date, "yyyyMM");
        endDate = null;
      } else {
        startDate = "";
        endDate = "";
      }

      if (startDate == "") {
        this.$message.error("请选择时间");
        return;
      }
      if (
        !_this.exportModel.areaNumberIds ||
        _this.exportModel.areaNumberIds.length == 0
      ) {
        _this.$message.error("请选择区域");
        return;
      }

      _this.exportLoading = true;

      switch (_this.exportModel.type) {
        case 1:
          window.open(
            "/baseApicost/exportSummaryReport?token=" +
              _this.$store.state.user.token +
              "&startDate=" +
              startDate +
              "&endDate=" +
              endDate +
              "&areaNumberIds=" +
              _this.exportModel.areaNumberIds
          );
          break;
        case 2:
          window.open(
            "/baseApicost/exportSummaryReportByClient?token=" +
              _this.$store.state.user.token +
              "&startDate=" +
              startDate +
              "&endDate=" +
              endDate +
              "&areaNumberIds=" +
              _this.exportModel.areaNumberIds
          );
          break;
        case 3:
          window.open(
            "/baseApicost/exportDebtDetailReport?token=" +
              _this.$store.state.user.token +
              "&startDate=" +
              startDate +
              "&areaNumberIds=" +
              _this.exportModel.areaNumberIds
          );
          break;
      }
      _this.exportLoading = false;
    },
    areaChange(options) {
      const _this = this;
      if (options) {
        const hasAll = options.includes(_this.areaAllValue);
        if (!hasAll && options.length === _this.area.length) {
          _this.exportModel.areaNumberIds.unshift(_this.areaAllValue);
        } else if (hasAll && options.length - 1 < _this.area.length) {
          _this.exportModel.areaNumberIds =
            _this.exportModel.areaNumberIds.filter(
              (item) => item != _this.areaAllValue
            );
        }
      }
    },
    selectAllArea(selected) {
      const _this = this;
      _this.exportModel.areaNumberIds = [];
      if (selected) {
        for (let item of _this.area) {
          _this.exportModel.areaNumberIds.push(item.pkBasicdataId);
        }
        _this.exportModel.areaNumberIds.unshift(_this.areaAllValue);
      }
    },
  },
  mounted() {
    this.loadDataProxy();
    getOneAll(selectNameToId("lessor")).then((res) => {
      this.lessor = res.data;
    });
    getBuildingName().then((res) => {
      this.buildingData = res.data;
    });
    getOneAll(selectNameToId("area")).then((res) => {
      const _this = this;
      _this.area = res.data;

      _this.selectAllArea(true);
    });
  },
};
</script>
<style scoped>
.div-table {
  height: calc(100% - 85px - 40px - 15px);
}
.el-upload {
  width: 100%;
  height: 110px;
  background-size: 100% 100%;
  background-image: url(../../assets/img/cost/costpz.png);
}

.el-dialog__body {
  height: 100%;
}

.dialog {
  padding: 40px;
}

.el-dialog .el-dialog__title {
  font-size: 16px;
}

.dialog .el-dialog .el-dialog__title {
  font-size: 16px;
  color: white;
}

.dialog .el-dialog .el-dialog__header {
  background-color: #409eff;
  margin-bottom: 20px;
  padding: 10px 20px;
}
</style>
